<template>
  <a-spin size="large" class="form_div" :spinning="spinning" tip="加载中..." >
    <a-form-model layout="inline" :ref="refsKey" class="form_div" :rules="rules" :model="personForm">
      <div style="width: 100%;display: inline-block;">
        <!-- <a-icon v-if="isEdit" type="delete" class="delete_btn" title="删除人员" @click="deteltePerson"/> -->
        <!-- <a-icon v-if="isEdit" type="interaction" class="check_btn" title="校验数据" @click="savePerson"/> -->
        <a-row :gutter="48" style="width: 100%;" class="form_row">
          <a-col
            @click.stop="() => {}"
            :xl="8"
            :sm="8"
            :md="8"
            :lg="8"
            :xs="24" >
            <a-form-model-item label="送达方式:" prop="sendway">
              <a-select allow-clear placeholder="请选择送达方式" v-model="personForm.sendway" style="width:220px" :disabled="!isEdit">
                <a-select-option v-for="item in Tp_sendwayList" :value="item.value" :key="item.value">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col
            @click.stop="() => {}"
            :xl="8"
            :sm="8"
            :md="8"
            :lg="8"
            :xs="24" >
            <a-form-model-item label="收件人:" prop="recipient">
              <a-select
                allow-clear
                placeholder="请选择收件人"
                v-model="personForm.recipient"
                @change="recipientChange"
                style="width:220px"
                :disabled="!isEdit"
              >
                <a-select-option v-for="(item, id) in recipientnameOption" :value="item.name" :key="id">
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col
            @click.stop="() => {}"
            :xl="8"
            :sm="8"
            :md="8"
            :lg="8"
            :xs="24" >
            <a-form-model-item label="发出时间:" prop="sendtime">
              <a-date-picker
                style="width:220px"
                v-model="personForm.sendtime"
                placeholder="请选择发出时间"
                valueFormat="yyyy-MM-DD"
                :allowClear="true"
                :disabled="!isEdit"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="48" style="width: 100%;" class="form_row">
          <a-col
            @click.stop="() => {}"
            :xl="8"
            :sm="8"
            :md="8"
            :lg="8"
            :xs="24" >
            <a-form-model-item label="联系号码:" prop="phone">
              <a-input v-model="personForm.phone" placeholder="请输入联系号码" style="width:220px" :disabled="!isEdit"/>
            </a-form-model-item>
          </a-col>
          <a-col
            @click.stop="() => {}"
            :xl="12"
            :sm="12"
            :md="12"
            :lg="12"
            :xs="24" >
            <a-form-model-item label="邮寄单号:" prop="postcode" v-if="personForm.sendway === Tp_sendwayValue.POST">
              <a-input v-model="personForm.postcode" placeholder="邮寄单号" style="width:420px" :disabled="!isEdit"/>
            </a-form-model-item>
          </a-col>

          <a-col
            @click.stop="() => {}"
            :xl="12"
            :sm="12"
            :md="12"
            :lg="12"
            :xs="24" >
            <a-form-model-item label="公告送达链接:" v-if="personForm.sendway === Tp_sendwayValue.PUBLIC">
              <a-input v-model="personForm.publicurl" placeholder="请输入公告送达链接" style="width:420px" :disabled="!isEdit"/>
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row :gutter="48" style="width: 100%;" class="form_row">
          <a-col
            @click.stop="() => {}"
            :xl="12"
            :sm="12"
            :md="12"
            :lg="12"
            :xs="24" >
            <a-form-model-item label="邮寄地址:" prop="address" v-if="personForm.sendway === Tp_sendwayValue.POST">
              <a-input v-model="personForm.address" placeholder="请输入邮寄地址" style="width:550px" :disabled="!isEdit"/>
            </a-form-model-item>
          </a-col>
          <a-col
            @click.stop="() => {}"
            :xl="12"
            :sm="12"
            :md="12"
            :lg="12"
            :xs="24" >
            <a-form-model-item label="物流信息:" v-if="personForm.sendway === Tp_sendwayValue.POST && !isEdit && personForm.postcode">
              <span class="post_span" @click="showPostInfo">{{ personForm.postcode || '' }}  <a-divider type="vertical" /> 查看 <a-icon type="eye" style="margin-left: 10px"/></span>
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row :gutter="48" style="width: 100%;" class="form_row">
          <a-col
            @click.stop="() => {}"
            :xl="12"
            :sm="12"
            :md="12"
            :lg="12"
            :xs="24" >
            <a-form-model-item label="送达回执:" v-if="personForm.sendway === Tp_sendwayValue.ELEC && !isEdit">
              <span v-if="isReceipt" style="color:green; margin: 10px 10px">
                对方已点击打开
                <a-divider type="vertical" />
                {{ `点击时间：${receiptDate}` }}
              </span>
              <span v-else style="color:orange; margin: 10px 10px">对方未点击</span>
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row :gutter="48" style="width: 100%;" class="form_row">
          <a-col :xxl="24" :lg="24" :sm="24" v-if="isEdit">
            <a-alert message="上传或删除图片后请点击暂存保存或填写完全后一键送达" style="width: 600px; margin-bottom: 10px;" banner />
            <a-form-model-item label="附件信息图片" prop="photoinfo">
              <a-upload
                accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PNG"
                style="padding-left:20px;display: inline-flex;"
                list-type="picture-card"
                :file-list="photoFileList"
                @preview="photoPreview"
                :customRequest="(file) => uploadFile(file)"
                :before-upload="(file) => beforeUpload(file)"
                :remove="(file) => minioRemove(file)"
              >
                <div v-if="photoFileList.length < 5">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">
                    上传附件信息图片
                  </div>
                </div>
              </a-upload>
              <a-modal width="800px" :bodyStyle="{ height: '350', overflow: 'auto' }" :visible="previewVisible" :footer="null" @cancel="photoCancel" >
                <img alt="photo" style="width: 100%" :src="previewImage" />
              </a-modal>

            </a-form-model-item>
          </a-col>

          <a-col :xxl="24" :lg="24" :sm="24" v-else-if="photoFileList && photoFileList.length > 0">
            <a-form-model-item label="附件信息图片" prop="photoinfo">
              <a-upload
                style="padding-left:20px;display: inline-flex;"
                list-type="picture-card"
                :file-list="photoFileList"
                @preview="photoPreview"
              >
              </a-upload>
              <a-modal width="800px" :bodyStyle="{ height: '350', overflow: 'auto' }" :visible="previewVisible" :footer="null" @cancel="photoCancel">
                <img alt="photo" style="width: 100%" :src="previewImage" />
              </a-modal>
            </a-form-model-item>
          </a-col>
        </a-row>
      </div>
      <div class="delete_btn" v-if="isEdit">
        <a-icon type="delete" @click="deteltePerson" itle="删除人员" />
      </div>
      <!-- <div class="operate_btn_div">
        <a-button v-if="isEdit" class="btn_primary_color" style="margin: 0px 20px;height: 24px" @click="deteltePerson" itle="删除人员"> 删除人员</a-button>
      </div> -->
      <ArrivePostProcess ref="arrivePostRef" :postCode="personForm.postcode" :postAddress="postAddress"/>
    </a-form-model>
  </a-spin>
</template>

<script>
import { Tp_sendwayList, Tp_sendwayValue } from '@/enumeration/Tp_sendway'
import { getReceiptById } from '@/api/arrive/apl_arrive_details'
import { St_receiptValue } from '@/enumeration/St_receipt'
import { minioUpload, minioRemove } from '@/api/base/file'
export default {
  props: {
    personInfo: {
      type: Object,
      default: () => {
      }
    },
    isEdit: {
      type: Boolean,
      default: true
    },
    recordid: {
      type: String,
      required: true
    }
  },
  async created () {
    this.photoFileList = []
    this.personForm = { ...this.personForm, ...this.personInfo }
    this.refsKey = 'arrivePersonForm' + this.personForm.id
    // 默认人员信息
    this.recipientnameOption = this.$store.state.arrive.recipientnameOption
    if (this.personForm.sendway == Tp_sendwayValue.POST) {
      this.postAddress = this.personForm.recipient + '，' + this.personForm.phone + '，' + this.personForm.address
    } else if (this.personForm.sendway == Tp_sendwayValue.ELEC && !this.isEdit) {
      this.queryDetailById()
    }
    if (this.personInfo && this.personInfo.photoInfoList) {
      this.photoFileList = this.personInfo.photoInfoList
      this.photoFileList = this.photoFileList.filter(el => el != null && el !== undefined)
      this.photoFileList.forEach(el => {
        if (el) {
          el.uid = el.id
          el.url = el.path
          el.status = 'done'
          el.name = el.filename
          el.flag = el.id
        }
      })
    } else {
      this.photoFileList = []
    }
    if (!this.isEdit) {
      this.rules = {}
    }
  },
  data () {
    return {
      personForm: {
        id: undefined, // id
        sendway: undefined, // 送达方式
        sendtime: undefined, // 送达时间
        address: undefined, // 送达地址
        recipient: undefined, // 送达人
        postcode: undefined, // 邮寄单号
        phone: undefined, // 联系电话
        istarget: 3201, // 是否是被申请人
        photoinfo: undefined, // 附件图片信息
        publicurl: undefined // 公告送达链接
      },
      rules: {
        recipient: [{ required: true, message: '请选择收件人', trigger: 'change' }],
        sendway: [{ required: true, message: '请选择送达方式', trigger: 'change' }],
        sendtime: [{ required: true, message: '请选择发出时间', trigger: 'change' }],
        phone: [{ required: true, validator: this.checkPhone }],
        address: [{ required: true, message: '请输入邮寄地址', trigger: 'change' }],
        postcode: [{ required: true, message: '请输入邮寄单号', trigger: 'change' }]
      },
      Tp_sendwayList: Tp_sendwayList,
      Tp_sendwayValue: Tp_sendwayValue,
      recipientnameOption: [],
      postAddress: '',
      isReceipt: false, // 是否接收到回执
      receiptDate: null, // 接受时间

      photoFileList: [], // 照片list
      previewVisible: false,
      previewImage: '',
      acceptFileType: '.jpg,.jpeg,.png,.JPG,.JPEG,.PNG',
      spinning: false
    }
  },
  components: {
    ArrivePostProcess: () => import('@/views/arrive/ArrivePostProcess.vue')
  },
  watch: {
    personForm: {
      // value 需要深度监听及默认先执行handler函数
      handler (val) {
        if (val) {
          this.$emit('setCache', val)
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    async queryDetailById () {
      const res = await getReceiptById(this.recordid)
      if (res.code == 0) {
        const details = res.data
        if (details && details.length > 0) {
          details.forEach(el => {
            if (el.personid && el.personid == this.personForm.id && el.status == St_receiptValue.DELIVERED) {
              this.isReceipt = true
              this.receiptDate = el.arrivetime
            }
          })
        }
      } else {
        this.$message.error('查询送达详情失败')
      }
    },

    checkPhone (rule, value, callback) {
      if (!value) {
        callback(new Error('请输入联系号码'))
      }
      if (value && !/^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$/.test(value)) {
        callback(new Error('请输入正确的联系号码'))
      }
      callback()
    },
    validate () {
      let validateResult = false
      this.$refs[this.refsKey].validate((valid) => {
        validateResult = valid
      })
      return validateResult
    },
    savePerson () {
      let validateResult = false
      this.$refs[this.refsKey].validate((valid) => {
        validateResult = valid
      })
      if (validateResult) {
        this.$emit('saveSingleTemp', this.recordid)
      }
    },
    recipientChange (val) {
      // 通过对应的值来设置身份证等默认值
      const selectPerson = this.recipientnameOption.filter((item) => item.name == val)[0]
      if (selectPerson) {
        if (selectPerson.personType == 'applicant') {
          this.personForm.address = selectPerson.addr
          this.personForm.phone = selectPerson.tel
          this.personForm.istarget = 3201 // 否
        } else if (selectPerson.personType == 'target') {
          this.personForm.address = selectPerson.address
          this.personForm.phone = selectPerson.phone
          this.personForm.istarget = 3200 // 是
        } else if (selectPerson.personType == 'third') {
          this.personForm.address = selectPerson.addr
          this.personForm.phone = selectPerson.tel
          this.personForm.istarget = 3201 // 否
        } else if (selectPerson.personType == 'agent') {
          this.personForm.address = selectPerson.addr
          this.personForm.phone = selectPerson.tel
          this.personForm.istarget = 3201 // 否
        }
      }
    },

    deteltePerson () {
      this.$confirm({
        title: '是否删除该人员？',
        onOk: () => {
        this.$emit('deletePerson', this.personForm.id)
        }
      })
    },
    getPerson () {
      // 文件uid进行拼接
      if (this.photoFileList && this.photoFileList.length > 0) {
        const fileIdList = []
        this.photoFileList.forEach(file => {
          fileIdList.push(file.uid)
        })
        this.personForm.photoinfo = fileIdList.join(',')
      } else {
        this.personForm.photoinfo = undefined
      }
      return this.personForm
    },
    showPostInfo () {
      if (this.personForm.postcode) {
        this.spinning = true
        this.$refs.arrivePostRef.queryPostInfo(() => {
          this.spinning = false
        })
      } else {
        this.$message.warn('邮寄单号为空')
      }
    },

    /**
    * 上传导入文件前验证文件类型
    */
    beforeUpload (file) {
      return new Promise((resolve, reject) => {
        // 文件格式是否为xls,xlsx
        const isAcceptType = file.name.toLowerCase().substr(file.name.lastIndexOf('.'))
        const acceptType = '.jpg,.jpeg,.png,.JPG,.JPEG,.PNG'
        if (!(acceptType.indexOf(isAcceptType) > -1)) {
          this.$message.warning('请上传' + acceptType + '格式文件')
          return reject(false)
        }
        // 文件小于10M
        const isLtSize = file.size / 1024 / 1024 < 10
        if (!isLtSize) {
          this.$message.warning('请上传10MB以内的文件')
          return reject(false)
        }
        return resolve(false)
      })
    },

    /**
     * 上传附件,没有用到附件请删除
     */
     uploadFile (data) {
      console.log(data)
      minioUpload(data.file).then((res) => {
        console.log('res', res)
        if (res.code !== 0) {
          this.$message.error('上传图片失败')
        } else {
          this.$message.success('上传图片成功')
          const url = res.data.url
          const file = {
            id: res.data.id,
            uid: res.data.id,
            name: res.data.filename,
            status: 'done',
            url: res.data.url,
            flag: data.file.uid
          }
          this.photoFileList.push(file)
          // this.infoForm.avatar = url
          // this.$emit('saveSingleTemp', this.recordid)
        }
      })
    },
    photoCancel () {
      this.previewVisible = false
    },
    photoPreview (file) {
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    minioRemove (file) {
      minioRemove ({ 'fileid': file.uid }).then((res) => {
        console.log('res', res)
        if (res.code !== 0) {
          console.log('删除文件失败', res)
        } else {
          this.photoFileList = this.photoFileList.filter(el => el.uid !== file.uid)
          this.personInfo.photoInfoList = this.photoFileList
          console.log('删除文件成功')
          // this.$emit('saveSingleTemp', this.recordid)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

 .form_div {
    background-color: #F8FAFD;
    width: 100%;
    padding: 0px 16px;
    margin: 10px;
    display: inline-block;
  }
  .form_row {
    margin-bottom: 6px;
  }
  .operate_btn_div {
    display: flex;
    align-items: center;
    justify-content: center;
    justify-items: center;
    margin: 14px 0px;
  }
  .delete_btn {
    display: inline-block;
    top: 40%;
    position: absolute;
    font-size: 18px;
    color: #0072C6;
    right: 10px;
  }
  .check_btn {
    display: flex;
    float: right;
    font-size: 24px;
    color: green;
    cursor: pointer;
    margin: 0 10px;
    z-index:999;
    position: absolute;
    right: 80px;
    top: 16px;
  }

  .post_span {
    font-family: Source Han Sans CN;
    font-weight: 500;
    font-size: 14px;
    color: #0072C6;
    line-height: 7px;
    margin: 10px 10px;
    cursor: pointer;
  }

</style>
